/*
 * Espere.java
 *
 * Created on 15 de febrero de 2006, 03:34 PM
 */

package ig.metrica.ui;

import ejb.metrica.seguridad.control.CuentaUsuarioControlBean;
import ejb.metrica.seguridad.control.LoginDTO;
import ejb.metrica.seguridad.entity.CuentausuarioDTO;
import ejb.metrica.seguridad.entity.RolesDTO;

import ig.util.ConexionServer;
import ig.util.Digest;
import ig.util.LoadProperties;
import ig.util.ejb.IGBean;
import java.rmi.RemoteException;
import java.util.Date;
import java.util.Hashtable;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.CreateException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 *
 * @author  jsanchez
 */
public class MLogin extends javax.swing.JDialog{
//    private static Logger log = Logger.getLogger(MLogin.class.getName());
    PrincipalMetrica frame=null;
    ModeloLogin modeloLogin=null;
    Properties propiedades=null;
    /** Creates new form Espere */
    public MLogin(PrincipalMetrica frame,Properties propiedades) {
        super(frame,"Login",true);
        this.propiedades=propiedades;
        this.frame=frame;
        initComponents();
        this.setLocationByPlatform(true);
        centrar();
        this.setJMenuBar(BarraMenu);
        this.setSize(330,165);
        if(propiedades!=null){
            String UserDefault=propiedades.getProperty("UserDefaultd");
            String loaduserdefault=propiedades.getProperty("loaduserdefault");            
            if(loaduserdefault!=null && loaduserdefault.trim().equals("true") &&(UserDefault!=null && !UserDefault.trim().equals(""))){
                this.User.setText(UserDefault);
                this.Password.requestFocusInWindow();
            }
            this.setVisible(true);
        }
    }
    public void centrar() {
        java.awt.Dimension dimensionScreen = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        java.awt.Rectangle dimensionPantalla = getBounds();
        setLocation((dimensionScreen.width - dimensionPantalla.width) / 2, (dimensionScreen.height - dimensionPantalla.height) / 2);
    }
    
    public Hashtable<String,Object> getSession() {
        return this.frame.getSession();
    }
    
    public MLogin(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    public char[] getPassword() {
        return Password.getPassword();
    }
    
    public String getUser() {
        return User.getText();
    }

    public void setMensaje(String mensaje){
        if(mensaje.equals("Ok"))
            Mensaje.setForeground(new java.awt.Color(0, 102, 255));
        else
            Mensaje.setForeground(new java.awt.Color(255, 51, 0));
        this.Mensaje.setText(mensaje);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        BarraMenu = new javax.swing.JMenuBar();
        Menu = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        jPanel2 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        User = new javax.swing.JTextField();
        Password = new javax.swing.JPasswordField();
        BAceptar = new javax.swing.JButton();
        BCancelar = new javax.swing.JButton();
        Mensaje = new javax.swing.JLabel();
        Progreso = new javax.swing.JProgressBar();

        Menu.setText("Servidor");

        jMenuItem2.setText("Propiedades");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        Menu.add(jMenuItem2);

        BarraMenu.add(Menu);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel3.setText("Usuario");

        jLabel4.setText("Clave");

        User.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                UserActionPerformed(evt);
            }
        });

        Password.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                PasswordActionPerformed(evt);
            }
        });

        BAceptar.setBackground(new java.awt.Color(204, 255, 204));
        BAceptar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ig/util/images/ok.png"))); // NOI18N
        BAceptar.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        BAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BAceptarActionPerformed(evt);
            }
        });

        BCancelar.setBackground(new java.awt.Color(255, 204, 204));
        BCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ig/util/images/cancel.png"))); // NOI18N
        BCancelar.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        BCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BCancelarActionPerformed(evt);
            }
        });

        Mensaje.setForeground(new java.awt.Color(255, 51, 0));
        Mensaje.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        Mensaje.setText("-");

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel2Layout.createSequentialGroup()
                        .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                            .add(jLabel4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .add(jLabel3))
                        .add(18, 18, 18)
                        .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(User, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
                            .add(Password, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                        .add(Mensaje, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(BAceptar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 46, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                        .add(BCancelar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 48, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(User, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(Password, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(Mensaje, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(BAceptar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(BCancelar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        Progreso.setFont(new java.awt.Font("Tahoma", 0, 3)); // NOI18N
        Progreso.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(Progreso, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 332, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(Progreso, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    
    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
        new PropiedadesJDBC(this.frame,true).setVisible(true);
    }//GEN-LAST:event_jMenuItem2ActionPerformed
    
    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        this.frame.dispose();
        System.exit(-1);
    }//GEN-LAST:event_formWindowClosing
            
    private void PasswordActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PasswordActionPerformed
        Progreso.setIndeterminate(true);
        setEnablePass(false);
        new ModeloLogin(this).start();
//        this.setValue(0);
    }//GEN-LAST:event_PasswordActionPerformed
    
    private void UserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_UserActionPerformed
        this.Password.requestFocusInWindow();
    }//GEN-LAST:event_UserActionPerformed
    
    private void BAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BAceptarActionPerformed
        Progreso.setIndeterminate(true);
        setEnablePass(false);        
        new ModeloLogin(this).start();
//        this.setValue(0);
    }//GEN-LAST:event_BAceptarActionPerformed
    
    private void BCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BCancelarActionPerformed
        System.exit(-1);
    }//GEN-LAST:event_BCancelarActionPerformed
        
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BAceptar;
    private javax.swing.JButton BCancelar;
    private javax.swing.JMenuBar BarraMenu;
    private javax.swing.JLabel Mensaje;
    private javax.swing.JMenu Menu;
    private javax.swing.JPasswordField Password;
    public javax.swing.JProgressBar Progreso;
    private javax.swing.JTextField User;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel2;
    // End of variables declaration//GEN-END:variables
    public Properties getPropiedades(){
        return this.propiedades;
    }
    
    public void cleanPassword() {
        this.Password.setText("");
    }
    
    public void conectar(String login) {
        frame.conectado(login);
    }
    
    public void desconectar(Hashtable<String,Object> obj){
        try {
            if(obj.size()>0){
                LoginDTO loginDTO=new LoginDTO();
                loginDTO.setID(Long.valueOf(obj.elements().nextElement().toString()));
                loginDTO.setUSUARIO(obj.keys().nextElement().trim());
                this.lookupCuentaUsuarioControlBean().desconectar(loginDTO);
            }
        } catch (RemoteException ex) {
            ex.printStackTrace();
        }
    }
    
    public ejb.metrica.seguridad.control.CuentaUsuarioControlBean lookupCuentaUsuarioControlBean() throws RemoteException {
        return new CuentaUsuarioControlBean();
        /*
        try {

            Properties prop = new Properties();
            prop.put( Context.INITIAL_CONTEXT_FACTORY, IGBean.INITIAL_CONTEXT_FACTORY);
            String Sockec = new ConexionServer().getSocketServer();
            prop.put( Context.PROVIDER_URL, Sockec);
            
            javax.naming.Context c = new javax.naming.InitialContext(prop);
            Object remote = c.lookup("CuentaUsuarioControlBean");
                        
             ejb.metrica.seguridad.control.CuentaUsuarioControlRemoteHome rv = (ejb.metrica.seguridad.control.CuentaUsuarioControlRemoteHome) javax.rmi.PortableRemoteObject.narrow(remote, ejb.metrica.seguridad.control.CuentaUsuarioControlRemoteHome.class);
             ejb.metrica.seguridad.control.CuentaUsuarioControlRemote login=rv.create();
             return login;
             
        } catch(javax.naming.NamingException ne) {
            ne.printStackTrace();
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,ne);
            throw new RemoteException(ne.getMessage());
        } catch(javax.ejb.CreateException ce) {
            ce.printStackTrace();
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,ce);
            throw new RemoteException(ce.getMessage());
        } catch(java.rmi.RemoteException re) {
            re.printStackTrace();
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,re);
            throw new RemoteException(re.getMessage());
        } catch(Exception re) {
            re.printStackTrace();
            //java.util.logging.Logger.getLogger(getClass().getName()).log(java.util.logging.Level.SEVERE,"exception caught" ,re);
            throw new RemoteException(re.getMessage());
        }*/
    }
    
    private ServiceLocator getServiceLocator() {
        return new ServiceLocator();
    }
    
    public  void setEnablePass(boolean que) {
        Password.setEnabled(que);
        BAceptar.setEnabled(que);
    }
}

/**
 *Modelo de MLogin
 **/
class ModeloLogin extends Thread{
    private MLogin panel=null;
    private ServiceLocator serviceLocator;
    
    public ModeloLogin(MLogin panel){
        this.panel=panel;
    }
    
    /*public static void main(){
        System.out.println(Digest.encriptar(""));
    }*/
    
    public void autenticar() throws InterruptedException, CreateException, RemoteException {
//        panel.Progreso.setIndeterminate(true);
            
        
        panel.setCursor(new java.awt.Cursor(java.awt.Cursor.WAIT_CURSOR));
        String PASSWORD="";
        for (int i = 0; i < panel.getPassword().length; i++) {
            PASSWORD=PASSWORD+panel.getPassword()[i];
        }
        String PASSWORD_ENCRIPTADO=Digest.encriptar(PASSWORD);
        String USER=panel.getUser();

        System.out.println("PASSWORD_ENCRIPTADO:"+PASSWORD_ENCRIPTADO);
        /*if(PASSWORD.trim().isEmpty()){

        }else if( PASSWORD.trim().equalsIgnoreCase(USER.trim()) ){
            try {
                Object obj = Class.forName("").newInstance();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }*/
        Object respuesta=null;
        try {
            respuesta=panel.lookupCuentaUsuarioControlBean().validarCuenta(new CuentausuarioDTO(1,PASSWORD_ENCRIPTADO,USER, METRICA.VERSION));
        } catch (RemoteException ex) {
            ex.printStackTrace();
            panel.setEnablePass(true);
            panel.setMensaje("Fall\u00F3 Servidor");
            panel.cleanPassword();
        }
        if(respuesta instanceof RolesDTO){
            panel.setMensaje("Ok");
            panel.getPropiedades().setProperty("UserDefaultd",USER);
            LoadProperties.storePropertiess(panel.getPropiedades(),"server/user.properties",new Date().toString());
            panel.getSession().put(((RolesDTO)respuesta).getUSUARIO(),((RolesDTO)respuesta).getID());
            panel.getSession().put("rol",((RolesDTO)respuesta).getId());
            panel.getSession().put("rol_dto",((RolesDTO)respuesta));
            panel.conectar(USER);
            panel.dispose();
        }else if(respuesta instanceof Boolean){
            panel.setEnablePass(true);
            panel.setMensaje("Fall\u00F3 Login");
            panel.cleanPassword();
        }else if(respuesta instanceof String){
            panel.setEnablePass(true);
            panel.setMensaje("Fall\u00F3 Versi\u00F3n: "+respuesta);
            panel.cleanPassword();
        }        
        panel.Progreso.setIndeterminate(false);
        panel.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        try {
            this.finalize();
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }
    @Override
    public void run(){
        try {
            try {
                this.autenticar();
            } catch (CreateException ex) {
                Logger.getLogger(ModeloLogin.class.getName()).log(Level.SEVERE, null, ex);
            } catch (RemoteException ex) {
                Logger.getLogger(ModeloLogin.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (InterruptedException ex) {}
    }
    
}
